const { prisma } = require('../config/prisma');

class OrderPrisma {
  constructor(data) {
    this.id = data.id;
    this.order_number = data.order_number;
    this.user_id = data.user_id;
    this.package_id = data.package_id;
    this.amount = data.amount;
    this.status = data.status;
    this.payment_method = data.payment_method;
    this.transaction_id = data.transaction_id;
    this.paid_at = data.paid_at;
    this.created_at = data.created_at;
    this.updated_at = data.updated_at;
    
    // 关联数据
    this.user = data.users;
    this.package = data.packages; // 保持向后兼容
    this.packages = data.packages; // 新的命名约定
  }

  /**
   * 生成订单号
   * @returns {string}
   */
  static generateOrderNumber() {
    const timestamp = Date.now();
    const random = Math.floor(Math.random() * 10000).toString().padStart(4, '0');
    return `ORD${timestamp}${random}`;
  }

  /**
   * 根据ID查找订单
   * @param {number} id 订单ID
   * @param {Object} options 查询选项
   * @returns {Promise<OrderPrisma|null>}
   */
  static async findById(id, options = {}) {
    const { include = {} } = options;
    
    const order = await prisma.orders.findUnique({
      where: { id: BigInt(id) },
      include: {
        users: include.user || false,
        packages: include.package || false
      }
    });
    
    return order ? new OrderPrisma(order) : null;
  }

  /**
   * 根据订单号查找订单
   * @param {string} orderNumber 订单号
   * @param {Object} options 查询选项
   * @returns {Promise<OrderPrisma|null>}
   */
  static async findByOrderNumber(orderNumber, options = {}) {
    const { include = {} } = options;
    
    const order = await prisma.orders.findUnique({
      where: { order_number: orderNumber },
      include: {
        users: include.user || false,
        packages: include.packages || false
      }
    });
    
    return order ? new OrderPrisma(order) : null;
  }

  /**
   * 获取订单列表（支持分页和筛选）
   * @param {Object} options 查询选项
   * @returns {Promise<{data: OrderPrisma[], pagination: Object}>}
   */
  static async getList(options = {}) {
    const {
      page = 1,
      pageSize = 10,
      payment_status,
      search,
      orderBy = { created_at: 'desc' }
    } = options;

    const skip = (page - 1) * pageSize;
    const take = parseInt(pageSize);

    // 构建查询条件
    const where = {};

    if (payment_status) {
      where.payment_status = payment_status;
    }

    if (search) {
      where.OR = [
        { order_number: { contains: search } },
        {
          users: {
            OR: [
              { nickname: { contains: search } },
              { phone_number: { contains: search } }
            ]
          }
        },
        {
          packages: {
            title: { contains: search }
          }
        }
      ];
    }

    // 包含关联数据
    const include = {
      users: {
        select: {
          id: true,
          nickname: true,
          phone_number: true
        }
      },
      packages: {
        select: {
          id: true,
          title: true,
          credits_amount: true
        }
      }
    };

    // 获取总数
    const total = await prisma.orders.count({ where });

    // 获取数据
    const orders = await prisma.orders.findMany({
      where,
      orderBy,
      skip,
      take,
      include
    });

    const totalPages = Math.ceil(total / pageSize);

    return {
      data: orders.map(order => new OrderPrisma(order)),
      pagination: {
        page: parseInt(page),
        pageSize: take,
        total,
        totalPages
      }
    };
  }

  /**
   * 根据用户ID查找订单列表
   * @param {number} userId 用户ID
   * @param {Object} options 查询选项
   * @returns {Promise<{orders: OrderPrisma[], total: number}>}
   */
  static async findByUserId(userId, options = {}) {
    const { 
      page = 1, 
      limit = 10, 
      orderBy = { created_at: 'desc' },
      include = {}
    } = options;
    
    const skip = (page - 1) * limit;
    const where = { user_id: BigInt(userId) };
    
    const [orders, total] = await Promise.all([
      prisma.orders.findMany({
        where,
        orderBy,
        skip,
        take: limit,
        include: {
          users: include.user || false,
          packages: include.package || false
        }
      }),
      prisma.orders.count({ where })
    ]);
    
    return {
      orders: orders.map(order => new OrderPrisma(order)),
      total
    };
  }

  /**
   * 获取所有订单列表（管理后台用）
   * @param {Object} options 查询选项
   * @returns {Promise<{orders: OrderPrisma[], total: number}>}
   */
  static async findAll(options = {}) {
    const { 
      page = 1, 
      limit = 10, 
      orderBy = { created_at: 'desc' },
      where = {},
      include = { user: true, package: true }
    } = options;
    
    const skip = (page - 1) * limit;
    
    const [orders, total] = await Promise.all([
      prisma.orders.findMany({
        where,
        orderBy,
        skip,
        take: limit,
        include: {
          users: include.user || false,
          packages: include.package || false
        }
      }),
      prisma.orders.count({ where })
    ]);
    
    return {
      orders: orders.map(order => new OrderPrisma(order)),
      total
    };
  }

  /**
   * 创建新订单
   * @param {Object} orderData 订单数据
   * @returns {Promise<OrderPrisma>}
   */
  static async create(orderData) {
    const order = await prisma.orders.create({
      data: {
        order_number: orderData.order_number || this.generateOrderNumber(),
        user_id: BigInt(orderData.user_id),
        package_id: parseInt(orderData.package_id),
        amount: orderData.amount,
        status: orderData.status || 'pending',
        payment_method: orderData.payment_method || null,
        transaction_id: orderData.transaction_id || null,
        paid_at: orderData.paid_at || null
      },
      include: {
        users: true,
        packages: true
      }
    });
    
    return new OrderPrisma(order);
  }

  /**
   * 更新订单状态
   * @param {number} id 订单ID
   * @param {Object} updateData 更新数据
   * @returns {Promise<OrderPrisma|null>}
   */
  static async update(id, updateData) {
    try {
      const order = await prisma.orders.update({
        where: { id: BigInt(id) },
        data: updateData,
        include: {
          users: true,
          packages: true
        }
      });
      
      return new OrderPrisma(order);
    } catch (error) {
      if (error.code === 'P2025') {
        return null; // 记录不存在
      }
      throw error;
    }
  }

  /**
   * 更新订单为已支付状态
   * @param {string} orderNumber 订单号
   * @param {Object} paymentData 支付数据
   * @returns {Promise<OrderPrisma|null>}
   */
  static async markAsPaid(orderNumber, paymentData = {}) {
    const updateData = {
      status: 'paid',
      paid_at: new Date(),
      ...paymentData
    };
    
    try {
      const order = await prisma.orders.update({
        where: { order_number: orderNumber },
        data: updateData,
        include: {
          users: true,
          packages: true
        }
      });
      
      return new OrderPrisma(order);
    } catch (error) {
      if (error.code === 'P2025') {
        return null; // 记录不存在
      }
      throw error;
    }
  }

  /**
   * 更新订单状态
   * @param {number} id 订单ID
   * @param {string} status 新状态
   * @returns {Promise<OrderPrisma>}
   */
  static async updateStatus(id, status) {
    try {
      const order = await prisma.orders.update({
        where: { id: BigInt(id) },
        data: {
          status,
          paid_at: status === 'completed' ? new Date() : null,
          updated_at: new Date()
        },
        include: {
          users: true,
          packages: true
        }
      });

      return new OrderPrisma(order);
    } catch (error) {
      if (error.code === 'P2025') {
        return null; // 记录不存在
      }
      throw error;
    }
  }

  /**
   * 转换为JSON对象
   * @returns {Object}
   */
  toJSON() {
    const result = {
      id: this.id?.toString(),
      order_number: this.order_number,
      user_id: this.user_id?.toString(),
      package_id: this.package_id,
      amount: parseFloat(this.amount),
      status: this.status,
      payment_status: this.status, // 为管理端兼容性添加
      payment_method: this.payment_method,
      transaction_id: this.transaction_id,
      paid_at: this.paid_at,
      created_at: this.created_at,
      updated_at: this.updated_at
    };
    
    if (this.user) {
      result.user = {
        id: this.user.id?.toString(),
        nickname: this.user.nickname,
        phone_number: this.user.phone_number
      };
    }
    
    if (this.package) {
      result.package = {
        id: this.package.id,
        title: this.package.title,
        credits_amount: this.package.credits_amount
      };
    }
    
    return result;
  }
}

module.exports = OrderPrisma;
